package com.example.administrator.myapplication.net.chain;

import android.util.Log;

import com.example.administrator.myapplication.net.ConnectionPool;
import com.example.administrator.myapplication.net.HttpClient;
import com.example.administrator.myapplication.net.HttpConnection;
import com.example.administrator.myapplication.net.HttpUrl;
import com.example.administrator.myapplication.net.Request;
import com.example.administrator.myapplication.net.Response;

public class ConnectionInterceptor implements Interceptor {
    String tag = "ConnectionInterceptor";

    @Override
    public Response intercept(InterceptorChain chain) throws Exception {
        Log.e("ConnectionInterceptor","连接拦截器");
        HttpClient httpClient = chain.call.client();
        ConnectionPool connectionPool = httpClient.connectionPool();
        Request request = chain.call.request();
        HttpUrl httpUrl = request.url();
        HttpConnection connection = connectionPool.get(httpUrl.getHost(), httpUrl.getPort());
        if (connection == null) {
            connection = new HttpConnection();
        } else {
            Log.e(tag, "从连接词中获得连接");
        }
        connection.setRequest(request);
        try {
            Response response = chain.process(connection);
            if (response.isKeepAlive()) {
                httpClient.connectionPool().put(connection);
            }else {
                connection.close();
            }
            return response;
        } catch (Exception e) {
            connection.close();
            throw e;
        }

    }
}
